const User = require('../models/user');
const Article = require('../models/article');
const CollectArticleList= require('../models/CollectArticleList');
const {Op} = require('sequelize');
//用户与收藏列表一对多关系
User.hasMany(CollectArticleList,{foreignKey:'user_id',sourceKey:'user_id'});
CollectArticleList.belongsTo(User,{foreignKey:'user_id',targetKey:'user_id'});

//问题与收藏列表一对多关系
Article.hasMany(CollectArticleList,{foreignKey:'article_id',sourceKey:'article_id'});
CollectArticleList.belongsTo(Article,{foreignKey:'article_id',targetKey:'article_id'});

class CollectArticleListsCtl{
  //查看特定用户的收藏列表
  async findByUserId(ctx){
    const { count,rows } = await CollectArticleList.findAndCountAll({
      where:{
        user_id:ctx.state.user.user_id
      },
    })
    ctx.body = {
      status:200,
      msg:'success',
      data:{
        count,
        data:rows
      }
    }
  }
  //添加新收藏
  async collectArticle(ctx){
    const article_id = ctx.params.id;
    const user_id = ctx.state.user.user_id
    const collect = await CollectArticleList.create({
      user_id,
      article_id
    });
    ctx.body = collect
  }
  //取消收藏
  async uncollectArticle(ctx){
    const article_id= ctx.params.id;
    const collect = await CollectArticleList.findOne({
      where:{
        [Op.and]:{
          article_id,
          user_id:ctx.state.user.user_id
        }
      }
    })
    await collect.destroy();
    ctx.status = 204
  }
}

module.exports = new CollectArticleListsCtl();
